package com.aabte.permissionframeworklearn.permission.service;

import com.aabte.permissionframeworklearn.permission.beans.PageQuery;
import com.aabte.permissionframeworklearn.permission.beans.PageResult;
import com.aabte.permissionframeworklearn.permission.common.RequestHolder;
import com.aabte.permissionframeworklearn.permission.exception.ParamException;
import com.aabte.permissionframeworklearn.permission.mapper.SysUserMapper;
import com.aabte.permissionframeworklearn.permission.model.SysUser;
import com.aabte.permissionframeworklearn.permission.param.UserParam;
import com.aabte.permissionframeworklearn.permission.util.BeanValidator;
import com.aabte.permissionframeworklearn.permission.util.IpUtil;
import com.aabte.permissionframeworklearn.permission.util.MD5Util;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Daniel
 */
@Service
public class SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysLogService sysLogService;

    public SysUser save(UserParam param) {

        BeanValidator.check(param);

        if (checkUsernameExist(param.getUsername())) {
            throw new ParamException("用户名已注册！");
        }
        if (checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用！");
        }
        if (checkEmailExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用！");
        }

        // TODO 随机生成密码
        // String password = PasswordUtil.randomPassword();
        String password = "123456";
        String encryptPassword = MD5Util.encrypt(password);

        SysUser sysUser = SysUser.builder()
                .username(param.getUsername())
                .deptId(param.getDeptId())
                .telephone(param.getTelephone())
                .mail(param.getMail())
                .remark(param.getRemark())
                .status(param.getStatus())
                .password(encryptPassword)
                .operator(RequestHolder.getCurrentUser().getUsername())
                .operateIp(IpUtil.getRemoteIpAddress(RequestHolder.getCurrentRequest()))
                .operateTime(new Date())
                .build();

        // TODO: sendEmail
        // MailUtil.send(mail);

        sysUserMapper.insertSelective(sysUser);
        sysLogService.saveUserLog(null, sysUser);
        return sysUser;
    }


    public SysUser update(UserParam param) {
        BeanValidator.check(param);

        if (checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用！");
        }
        if (checkEmailExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用！");
        }

        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的用户不存在");

        SysUser after = SysUser.builder()
                .id(param.getId())
                .username(param.getUsername())
                .deptId(param.getDeptId())
                .telephone(param.getTelephone())
                .mail(param.getMail())
                .remark(param.getRemark())
                .status(param.getStatus())
                .operator(RequestHolder.getCurrentUser().getUsername())
                .operateIp(IpUtil.getRemoteIpAddress(RequestHolder.getCurrentRequest()))
                .operateTime(new Date())
                .build();

        sysUserMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveUserLog(before, after);
        return after;
    }

    public PageResult<SysUser> queryUsersByDeptId(Long deptId, PageQuery pageQuery) {

        BeanValidator.check(pageQuery);

        long total = sysUserMapper.countByDeptId(deptId);
        if (0 < total) {
            List<SysUser> users = sysUserMapper.getPageByDeptId(deptId, pageQuery);
            return PageResult.<SysUser>builder().data(users).total(total).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    public SysUser queryUserByKeyword(String keyword) {
        return sysUserMapper.findByKeyword(keyword);
    }

    public List<SysUser> getAll() {
        return sysUserMapper.getAll();
    }

    private boolean checkUsernameExist(String username) {
        return sysUserMapper.countByUserName(username) > 0;
    }


    private boolean checkEmailExist(String mail, Long id) {
        return sysUserMapper.countByMail(mail, id) > 0;
    }

    private boolean checkTelephoneExist(String telephone, Long id) {
        return sysUserMapper.countByTelephone(telephone, id) > 0;
    }

}
